<template>
  <div class="document-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">文档管理</h1>
      <p class="page-description">项目文档的集中管理、版本控制和协作共享</p>
    </div>

    <!-- 文档统计卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon total">
              <el-icon><Document /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ documentOverview.totalDocs }}</div>
              <div class="card-label">总文档数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon shared">
              <el-icon><Share /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ documentOverview.sharedDocs }}</div>
              <div class="card-label">共享文档</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon versions">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ documentOverview.versions }}</div>
              <div class="card-label">版本总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon storage">
              <el-icon><FolderOpened /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ documentOverview.storageUsed }}</div>
              <div class="card-label">存储使用</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 文档分类和操作 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧文档分类树 -->
      <el-col :xs="24" :lg="6">
        <el-card class="category-card">
          <template #header>
            <div class="card-header">
              <span>文档分类</span>
              <el-button size="small" @click="showCategoryDialog = true">
                <el-icon><Plus /></el-icon>
              </el-button>
            </div>
          </template>
          <el-tree
            :data="categoryTree"
            :props="treeProps"
            node-key="id"
            :default-expand-all="true"
            :highlight-current="true"
            @node-click="handleCategoryClick"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <el-icon>
                  <Folder v-if="!data.isFile" />
                  <Document v-else />
                </el-icon>
                <span class="node-label">{{ node.label }}</span>
                <span class="node-count" v-if="!data.isFile">({{ data.count || 0 }})</span>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧文档列表 -->
      <el-col :xs="24" :lg="18">
        <el-card class="document-list-card">
          <template #header>
            <div class="section-header">
              <span>{{ currentCategoryName }}</span>
              <div class="header-actions">
                <el-upload
                  :action="uploadUrl"
                  :before-upload="beforeUpload"
                  :on-success="handleUploadSuccess"
                  :show-file-list="false"
                  multiple
                >
                  <el-button type="primary">
                    <el-icon><Upload /></el-icon>
                    上传文档
                  </el-button>
                </el-upload>
                <el-button @click="showNewFolderDialog = true">
                  <el-icon><FolderAdd /></el-icon>
                  新建文件夹
                </el-button>
                <el-button @click="exportDocumentData">
                  <el-icon><Download /></el-icon>
                  导出列表
                </el-button>
              </div>
            </div>
          </template>

          <!-- 搜索筛选 -->
          <div class="search-filters">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="8" :md="6">
                <el-input
                  v-model="documentFilters.keyword"
                  placeholder="搜索文档名称"
                  clearable
                  @input="handleDocumentSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-select v-model="documentFilters.type" placeholder="文档类型" clearable>
                  <el-option label="Word文档" value="doc" />
                  <el-option label="Excel表格" value="excel" />
                  <el-option label="PDF文档" value="pdf" />
                  <el-option label="图片" value="image" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-select v-model="documentFilters.status" placeholder="文档状态" clearable>
                  <el-option label="草稿" value="draft" />
                  <el-option label="审核中" value="reviewing" />
                  <el-option label="已发布" value="published" />
                  <el-option label="已归档" value="archived" />
                </el-select>
              </el-col>
              <el-col :xs="24" :sm="24" :md="6">
                <el-button type="primary" @click="handleDocumentSearch">搜索</el-button>
                <el-button @click="resetDocumentFilters">重置</el-button>
              </el-col>
            </el-row>
          </div>

          <!-- 视图切换 -->
          <div class="view-controls">
            <el-radio-group v-model="viewMode" size="small">
              <el-radio-button label="list">列表视图</el-radio-button>
              <el-radio-button label="grid">网格视图</el-radio-button>
            </el-radio-group>
          </div>

          <!-- 列表视图 -->
          <div v-if="viewMode === 'list'">
            <el-table
              :data="filteredDocumentList"
              v-loading="documentLoading"
              stripe
              style="width: 100%"
            >
              <el-table-column width="50">
                <template #default="{ row }">
                  <el-icon class="file-icon" :class="getFileIconClass(row.type)">
                    <component :is="getFileIcon(row.type)" />
                  </el-icon>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="文档名称" min-width="200">
                <template #default="{ row }">
                  <div class="file-name" @click="previewDocument(row)">
                    {{ row.name }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="size" label="大小" width="100">
                <template #default="{ row }">
                  {{ formatFileSize(row.size) }}
                </template>
              </el-table-column>
              <el-table-column prop="type" label="类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="getFileTypeColor(row.type)">{{ getFileTypeLabel(row.type) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="version" label="版本" width="80" />
              <el-table-column prop="creator" label="创建者" width="100" />
              <el-table-column prop="updateTime" label="更新时间" width="150" />
              <el-table-column label="操作" width="250" fixed="right">
                <template #default="{ row }">
                  <el-button size="small" @click="previewDocument(row)">预览</el-button>
                  <el-button size="small" @click="downloadDocument(row)">下载</el-button>
                  <el-button size="small" type="info" @click="showVersionHistory(row)">版本</el-button>
                  <el-button size="small" type="warning" @click="shareDocument(row)">共享</el-button>
                  <el-dropdown trigger="click">
                    <el-button size="small">更多<el-icon><ArrowDown /></el-icon></el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="editDocument(row)">编辑</el-dropdown-item>
                        <el-dropdown-item @click="moveDocument(row)">移动</el-dropdown-item>
                        <el-dropdown-item @click="copyDocument(row)">复制</el-dropdown-item>
                        <el-dropdown-item divided @click="deleteDocument(row)">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 网格视图 -->
          <div v-else class="grid-view">
            <el-row :gutter="20">
              <el-col
                v-for="doc in filteredDocumentList"
                :key="doc.id"
                :xs="24" :sm="12" :md="8" :lg="6"
                class="grid-item"
              >
                <el-card class="document-card" @click="previewDocument(doc)">
                  <div class="document-preview">
                    <el-icon class="preview-icon" :class="getFileIconClass(doc.type)">
                      <component :is="getFileIcon(doc.type)" />
                    </el-icon>
                  </div>
                  <div class="document-info">
                    <div class="document-name" :title="doc.name">{{ doc.name }}</div>
                    <div class="document-meta">
                      <span class="file-size">{{ formatFileSize(doc.size) }}</span>
                      <el-tag size="small" :type="getStatusType(doc.status)">{{ getStatusLabel(doc.status) }}</el-tag>
                    </div>
                    <div class="document-actions">
                      <el-button size="small" @click.stop="downloadDocument(doc)">下载</el-button>
                      <el-button size="small" type="info" @click.stop="shareDocument(doc)">共享</el-button>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 分页 -->
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="documentPagination.currentPage"
              v-model:page-size="documentPagination.pageSize"
              :page-sizes="[12, 24, 48, 96]"
              :total="documentPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleDocumentSizeChange"
              @current-change="handleDocumentCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新建分类对话框 -->
    <el-dialog
      v-model="showCategoryDialog"
      title="新建分类"
      width="400px"
      @close="resetCategoryForm"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级分类">
          <el-tree-select
            v-model="categoryForm.parentId"
            :data="categoryTree"
            :props="treeProps"
            placeholder="选择父级分类（可选）"
            clearable
            check-strictly
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCategoryDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCategory" :loading="categorySaving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog
      v-model="showNewFolderDialog"
      title="新建文件夹"
      width="400px"
      @close="resetFolderForm"
    >
      <el-form
        ref="folderFormRef"
        :model="folderForm"
        :rules="folderRules"
        label-width="80px"
      >
        <el-form-item label="文件夹名" prop="name">
          <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="folderForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入文件夹描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showNewFolderDialog = false">取消</el-button>
        <el-button type="primary" @click="createFolder" :loading="folderCreating">创建</el-button>
      </template>
    </el-dialog>

    <!-- 文档共享对话框 -->
    <el-dialog
      v-model="showShareDialog"
      title="文档共享"
      width="500px"
      @close="resetShareForm"
    >
      <el-form
        ref="shareFormRef"
        :model="shareForm"
        label-width="100px"
      >
        <el-form-item label="共享给">
          <el-select
            v-model="shareForm.users"
            multiple
            placeholder="选择用户"
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限设置">
          <el-radio-group v-model="shareForm.permission">
            <el-radio label="read">只读</el-radio>
            <el-radio label="edit">编辑</el-radio>
            <el-radio label="admin">管理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有效期">
          <el-date-picker
            v-model="shareForm.expireDate"
            type="date"
            placeholder="选择过期时间（可选）"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="共享链接">
          <el-switch v-model="shareForm.enableLink" active-text="启用链接共享" />
        </el-form-item>
        <el-form-item v-if="shareForm.enableLink" label="链接密码">
          <el-input v-model="shareForm.linkPassword" placeholder="设置访问密码（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showShareDialog = false">取消</el-button>
        <el-button type="primary" @click="saveShare" :loading="shareSaving">确定</el-button>
      </template>
    </el-dialog>

    <!-- 版本历史对话框 -->
    <el-dialog
      v-model="showVersionDialog"
      title="版本历史"
      width="700px"
    >
      <el-table :data="versionList" stripe>
        <el-table-column prop="version" label="版本" width="80" />
        <el-table-column prop="description" label="更新说明" min-width="200" />
        <el-table-column prop="creator" label="创建者" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column prop="size" label="大小" width="100">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="downloadVersion(row)">下载</el-button>
            <el-button size="small" type="warning" @click="restoreVersion(row)">恢复</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document,
  Share,
  Clock,
  FolderOpened,
  Plus,
  Upload,
  FolderAdd,
  Download,
  Search,
  Folder,
  ArrowDown
} from '@element-plus/icons-vue'

// 响应式数据
const documentOverview = ref({
  totalDocs: 156,
  sharedDocs: 42,
  versions: 89,
  storageUsed: '2.3GB'
})

// 文档分类
const showCategoryDialog = ref(false)
const categorySaving = ref(false)
const categoryFormRef = ref()
const currentCategoryId = ref(1)
const currentCategoryName = ref('项目文档')

const categoryTree = ref([
  {
    id: 1,
    label: '项目文档',
    count: 45,
    children: [
      { id: 11, label: '需求文档', count: 12 },
      { id: 12, label: '设计文档', count: 18 },
      { id: 13, label: '技术文档', count: 15 }
    ]
  },
  {
    id: 2,
    label: '会议记录',
    count: 28,
    children: [
      { id: 21, label: '项目启动会', count: 5 },
      { id: 22, label: '进度评审会', count: 12 },
      { id: 23, label: '技术讨论会', count: 11 }
    ]
  },
  {
    id: 3,
    label: '合同文件',
    count: 15
  },
  {
    id: 4,
    label: '培训资料',
    count: 22
  }
])

const treeProps = {
  children: 'children',
  label: 'label'
}

const categoryForm = reactive({
  name: '',
  parentId: null,
  description: ''
})

const categoryRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
}

// 文件夹管理
const showNewFolderDialog = ref(false)
const folderCreating = ref(false)
const folderFormRef = ref()

const folderForm = reactive({
  name: '',
  description: ''
})

const folderRules = {
  name: [{ required: true, message: '请输入文件夹名称', trigger: 'blur' }]
}

// 文档管理
const documentLoading = ref(false)
const viewMode = ref('list')
const uploadUrl = '/api/documents/upload'

const documentFilters = reactive({
  keyword: '',
  type: '',
  status: ''
})

const documentPagination = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0
})

const documentList = ref([
  {
    id: 1,
    name: '项目需求规格说明书.docx',
    type: 'doc',
    size: 2048576,
    status: 'published',
    version: 'v2.1',
    creator: '张三',
    updateTime: '2024-01-15 14:30:00',
    categoryId: 11
  },
  {
    id: 2,
    name: '系统架构设计图.pdf',
    type: 'pdf',
    size: 5242880,
    status: 'published',
    version: 'v1.3',
    creator: '李四',
    updateTime: '2024-01-14 16:45:00',
    categoryId: 12
  },
  {
    id: 3,
    name: '数据库设计文档.xlsx',
    type: 'excel',
    size: 1048576,
    status: 'reviewing',
    version: 'v1.0',
    creator: '王五',
    updateTime: '2024-01-13 10:20:00',
    categoryId: 13
  },
  {
    id: 4,
    name: '项目启动会议记录.docx',
    type: 'doc',
    size: 512000,
    status: 'published',
    version: 'v1.0',
    creator: '赵六',
    updateTime: '2024-01-12 09:15:00',
    categoryId: 21
  },
  {
    id: 5,
    name: '界面原型图.png',
    type: 'image',
    size: 3145728,
    status: 'draft',
    version: 'v0.8',
    creator: '钱七',
    updateTime: '2024-01-11 15:30:00',
    categoryId: 12
  }
])

// 文档共享
const showShareDialog = ref(false)
const shareSaving = ref(false)
const shareFormRef = ref()
const currentDocument = ref(null)

const shareForm = reactive({
  users: [],
  permission: 'read',
  expireDate: '',
  enableLink: false,
  linkPassword: ''
})

// 版本历史
const showVersionDialog = ref(false)
const versionList = ref([
  {
    id: 1,
    version: 'v2.1',
    description: '更新需求分析章节，添加用户故事',
    creator: '张三',
    createTime: '2024-01-15 14:30:00',
    size: 2048576
  },
  {
    id: 2,
    version: 'v2.0',
    description: '重构文档结构，优化内容组织',
    creator: '张三',
    createTime: '2024-01-10 11:20:00',
    size: 1945600
  },
  {
    id: 3,
    version: 'v1.5',
    description: '添加功能模块详细说明',
    creator: '李四',
    createTime: '2024-01-05 16:45:00',
    size: 1843200
  }
])

// 用户列表
const userList = ref([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' },
  { id: 4, name: '赵六' },
  { id: 5, name: '钱七' }
])

// 计算属性
const filteredDocumentList = computed(() => {
  let filtered = documentList.value.filter(doc => 
    doc.categoryId === currentCategoryId.value || currentCategoryId.value === 1
  )
  
  if (documentFilters.keyword) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(documentFilters.keyword.toLowerCase())
    )
  }
  
  if (documentFilters.type) {
    filtered = filtered.filter(item => item.type === documentFilters.type)
  }
  
  if (documentFilters.status) {
    filtered = filtered.filter(item => item.status === documentFilters.status)
  }
  
  documentPagination.total = filtered.length
  
  const start = (documentPagination.currentPage - 1) * documentPagination.pageSize
  const end = start + documentPagination.pageSize
  
  return filtered.slice(start, end)
})

// 方法
const getFileIcon = (type: string) => {
  const icons = {
    doc: 'Document',
    excel: 'Document',
    pdf: 'Document',
    image: 'Picture',
    other: 'Document'
  }
  return icons[type] || 'Document'
}

const getFileIconClass = (type: string) => {
  const classes = {
    doc: 'doc-icon',
    excel: 'excel-icon',
    pdf: 'pdf-icon',
    image: 'image-icon',
    other: 'other-icon'
  }
  return classes[type] || 'other-icon'
}

const getFileTypeLabel = (type: string) => {
  const labels = {
    doc: 'Word',
    excel: 'Excel',
    pdf: 'PDF',
    image: '图片',
    other: '其他'
  }
  return labels[type] || '未知'
}

const getFileTypeColor = (type: string) => {
  const colors = {
    doc: 'primary',
    excel: 'success',
    pdf: 'danger',
    image: 'warning',
    other: 'info'
  }
  return colors[type] || 'default'
}

const getStatusType = (status: string) => {
  const types = {
    draft: 'info',
    reviewing: 'warning',
    published: 'success',
    archived: 'default'
  }
  return types[status] || 'default'
}

const getStatusLabel = (status: string) => {
  const labels = {
    draft: '草稿',
    reviewing: '审核中',
    published: '已发布',
    archived: '已归档'
  }
  return labels[status] || status
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 分类管理方法
const handleCategoryClick = (data: any) => {
  currentCategoryId.value = data.id
  currentCategoryName.value = data.label
  documentPagination.currentPage = 1
}

const saveCategory = async () => {
  if (!categoryFormRef.value) return
  
  try {
    await categoryFormRef.value.validate()
    categorySaving.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const newCategory = {
      id: Date.now(),
      label: categoryForm.name,
      count: 0,
      children: []
    }
    
    if (categoryForm.parentId) {
      // 添加到父级分类
      const findAndAdd = (nodes: any[]) => {
        for (const node of nodes) {
          if (node.id === categoryForm.parentId) {
            if (!node.children) node.children = []
            node.children.push(newCategory)
            return true
          }
          if (node.children && findAndAdd(node.children)) {
            return true
          }
        }
        return false
      }
      findAndAdd(categoryTree.value)
    } else {
      // 添加为根级分类
      categoryTree.value.push(newCategory)
    }
    
    ElMessage.success('分类创建成功')
    showCategoryDialog.value = false
    resetCategoryForm()
  } catch (error) {
    console.error('保存分类失败:', error)
  } finally {
    categorySaving.value = false
  }
}

const resetCategoryForm = () => {
  Object.assign(categoryForm, {
    name: '',
    parentId: null,
    description: ''
  })
  if (categoryFormRef.value) {
    categoryFormRef.value.clearValidate()
  }
}

// 文件夹管理方法
const createFolder = async () => {
  if (!folderFormRef.value) return
  
  try {
    await folderFormRef.value.validate()
    folderCreating.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('文件夹创建成功')
    showNewFolderDialog.value = false
    resetFolderForm()
  } catch (error) {
    console.error('创建文件夹失败:', error)
  } finally {
    folderCreating.value = false
  }
}

const resetFolderForm = () => {
  Object.assign(folderForm, {
    name: '',
    description: ''
  })
  if (folderFormRef.value) {
    folderFormRef.value.clearValidate()
  }
}

// 文档管理方法
const handleDocumentSearch = () => {
  documentPagination.currentPage = 1
}

const resetDocumentFilters = () => {
  documentFilters.keyword = ''
  documentFilters.type = ''
  documentFilters.status = ''
  documentPagination.currentPage = 1
}

const handleDocumentSizeChange = (size: number) => {
  documentPagination.pageSize = size
  documentPagination.currentPage = 1
}

const handleDocumentCurrentChange = (page: number) => {
  documentPagination.currentPage = page
}

const beforeUpload = (file: File) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
  }
  return isLt10M
}

const handleUploadSuccess = (response: any, file: File) => {
  ElMessage.success('文件上传成功')
  // 刷新文档列表
}

const previewDocument = (document: any) => {
  ElMessage.info('文档预览功能开发中')
}

const downloadDocument = (document: any) => {
  ElMessage.success(`开始下载: ${document.name}`)
}

const editDocument = (document: any) => {
  ElMessage.info('文档编辑功能开发中')
}

const moveDocument = (document: any) => {
  ElMessage.info('文档移动功能开发中')
}

const copyDocument = (document: any) => {
  ElMessage.info('文档复制功能开发中')
}

const deleteDocument = async (document: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档"${document.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = documentList.value.findIndex(item => item.id === document.id)
    if (index > -1) {
      documentList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const exportDocumentData = () => {
  ElMessage.success('文档列表导出功能开发中')
}

// 文档共享方法
const shareDocument = (document: any) => {
  currentDocument.value = document
  showShareDialog.value = true
}

const saveShare = async () => {
  try {
    shareSaving.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('文档共享设置成功')
    showShareDialog.value = false
    resetShareForm()
  } catch (error) {
    console.error('保存共享设置失败:', error)
  } finally {
    shareSaving.value = false
  }
}

const resetShareForm = () => {
  Object.assign(shareForm, {
    users: [],
    permission: 'read',
    expireDate: '',
    enableLink: false,
    linkPassword: ''
  })
}

// 版本历史方法
const showVersionHistory = (document: any) => {
  currentDocument.value = document
  showVersionDialog.value = true
}

const downloadVersion = (version: any) => {
  ElMessage.success(`开始下载版本: ${version.version}`)
}

const restoreVersion = async (version: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复到版本 ${version.version} 吗？`,
      '确认恢复',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.success('版本恢复成功')
  } catch {
    ElMessage.info('已取消恢复')
  }
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.document-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

/* 概览卡片样式 */
.overview-cards {
  margin-bottom: 24px;
}

.overview-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  margin-right: 16px;
}

.card-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.shared {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.versions {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.card-icon.storage {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

/* 主要内容区域 */
.main-content {
  margin-bottom: 24px;
}

.category-card {
  height: fit-content;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-label {
  flex: 1;
}

.node-count {
  color: #909399;
  font-size: 12px;
}

/* 文档列表区域 */
.document-list-card {
  min-height: 600px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-filters {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 6px;
}

.view-controls {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 文件图标样式 */
.file-icon {
  font-size: 20px;
}

.file-icon.doc-icon {
  color: #2b579a;
}

.file-icon.excel-icon {
  color: #217346;
}

.file-icon.pdf-icon {
  color: #d83b01;
}

.file-icon.image-icon {
  color: #ca5010;
}

.file-icon.other-icon {
  color: #605e5c;
}

.file-name {
  cursor: pointer;
  color: #409eff;
}

.file-name:hover {
  text-decoration: underline;
}

/* 网格视图样式 */
.grid-view {
  margin-bottom: 20px;
}

.grid-item {
  margin-bottom: 20px;
}

.document-card {
  cursor: pointer;
  transition: all 0.3s;
  height: 200px;
}

.document-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.document-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  background-color: #f5f7fa;
}

.preview-icon {
  font-size: 48px;
}

.document-info {
  padding: 12px;
}

.document-name {
  font-weight: 500;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.document-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 12px;
  color: #909399;
}

.document-actions {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .document-management {
    padding: 12px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .main-content .el-col:first-child {
    margin-bottom: 20px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .card-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .card-icon {
    margin-right: 0;
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .card-value {
    font-size: 24px;
  }
  
  .search-filters .el-row {
    flex-direction: column;
  }
  
  .search-filters .el-col {
    margin-bottom: 12px;
  }
  
  .view-controls {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 18px;
  }
  
  .card-value {
    font-size: 20px;
  }
  
  .header-actions {
    flex-direction: column;
  }
  
  .document-card {
    height: 180px;
  }
  
  .document-preview {
    height: 80px;
  }
  
  .preview-icon {
    font-size: 36px;
  }
}
</style>